package com.iraeta.service.sys.impl;


import cn.hutool.core.date.DateUtil;
import com.iraeta.Config;
import com.iraeta.common.Constants;
import com.iraeta.dao.main.sys.SysFilesDao;
import com.iraeta.entity.main.SysFiles;
import com.iraeta.service.sys.ISysFilesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * 文件上传Service业务层处理
 * 
 * @author iraeta
 * @date 2023-11-04
 */
@Service
public class SysFilesServiceImpl implements ISysFilesService
{
    @Autowired
    private SysFilesDao sysFilesMapper;
    @Autowired
    Config config;

    public SysFiles selectSysFilesByFId(Long fId)
    {
        return sysFilesMapper.selectSysFilesByFId(fId);
    }

    public List<SysFiles> selectSysFilesList(int entityTypeId, long entityId)
    {
        SysFiles sysFiles = new SysFiles(entityTypeId, entityId);
        return sysFilesMapper.selectSysFilesList(sysFiles);
    }

    @Override
    public int insertSysFiles(SysFiles sysFiles)
    {
        sysFiles.setCreateTime(DateUtil.parseDate(DateUtil.now()));
        return sysFilesMapper.insertSysFiles(sysFiles);
    }

    @Override
    public int deleteSysFilesByFIds(Long[] fIds)
    {
        for(Long fId : fIds){
            this.deleteSysFilesByFId(fId);
        }
        return 0;
    }

    @Override
    public int deleteSysFilesByFId(Long fId)
    {
        SysFiles sysFiles = this.selectSysFilesByFId(fId);
        String realFilePath = config.profile + sysFiles.getFilePath().substring( Constants.RESOURCE_PREFIX.length());
        File deleteFile = new File(realFilePath);
        if(deleteFile.exists()){
            deleteFile.delete();
        }
        return sysFilesMapper.deleteSysFilesByFId(fId);
    }

    @Override
    public void updateSysFilesEntityId(long oldEntityId, long newEntityId) {
        sysFilesMapper.updateSysFilesEntityId(oldEntityId, newEntityId);
    }
}
